﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestWeb
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Display();
            }
        }

        private void Display()
        {
            string sql = "select * from Articles";
            GridView1.DataSource = DbHelper.GetDataTable(sql);
            GridView1.DataBind();
        }
        private string GetValue(int rowIndex, int col)
        {
            var value = ((TextBox)GridView1.Rows[rowIndex].Cells[col].Controls[0]).Text.Trim();
            return value;
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            Display();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var isOk = int.TryParse(GridView1.DataKeys[e.RowIndex].Value.ToString(),out int id);

            var title = GetValue(e.RowIndex, 1);
            var author = GetValue(e.RowIndex, 2);
            var content = GetValue(e.RowIndex, 3);
            var remarks = GetValue(e.RowIndex, 4);

            string sql = string.Empty;

            if (isOk)
            {
                sql = string.Format("update Articles set Title='{0}',Author='{1}',Content='{2}',Remarks='{3}' where id={4}", title,author,content,remarks,id);              
            }
            else
            {
                sql = string.Format("insert into Articles(Title,Author,Content,Remarks) values('{0}','{1}','{2}','{3}')",title,author,content,remarks);
            }

            DbHelper.Modification(sql);

            GridView1.EditIndex = -1;
            Display();


        }



        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            Display();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = (int)GridView1.DataKeys[e.RowIndex].Value;
            string sql = "delete Articles where id=" + id + "";

            DbHelper.Modification(sql);

            Display();


        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            string sql = "select * from Articles";
            DataTable table = DbHelper.GetDataTable(sql);

            table.Rows.Add(table.NewRow());

            GridView1.EditIndex = GridView1.Rows.Count;

            GridView1.DataSource = table;
            GridView1.DataBind();
        }
    }
}